These are the projects and labs completed for Data Visualization (STAT 302) - Spring 2020.


Favorite Labs
Lab 05
Lab 08

L01 ggplot overview

Overview

The goals of this lab are to (1) ensure that the major software for this course is properly installed and functional, (2) develop and follow a proper workflow, and (3) work together to construct a few plots to explore a dataset using ggplot2 — demonstration of the utility and power of ggplot2.

Don’t worry if you cannot do everything here by yourself. You are just getting started and the learning curve is steep, but remember that the instructional team and your classmates will be there to provide support. Persevere and put forth an honest effort and this course will payoff.

Load Packages tidyverse, ggstance, skimr


Dataset

We’ll be using data from the lego package which is already in the /data subdirectory, along with many other processed datasets, as part of the zipped folder for this lab.

Exercise 1

Let’s look at some interesting patterns in the history of LEGO! We’ll be using data from the lego package located data/legosets.rda. We will work through this exercise together in class.

1a Inspect the data

The lego package provides a helpful dataset some interesting variables. Let’s take a quick look at the data.

## Rows: 6,172
## Columns: 14
## $ Item_Number  <chr> "10246", "10247", "10248", "10249", "10581", "10582", ...
## $ Name         <chr> "Detective's Office", "Ferris Wheel", "Ferrari F40", "...
## $ Year         <int> 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, ...
## $ Theme        <chr> "Advanced Models", "Advanced Models", "Advanced Models...
## $ Subtheme     <chr> "Modular Buildings", "Fairground", "Vehicles", "Winter...
## $ Pieces       <int> 2262, 2464, 1158, 898, 13, 39, 32, 105, 13, 11, 52, 13...
## $ Minifigures  <int> 6, 10, NA, NA, 1, 2, 2, 3, 2, 2, 3, 1, NA, NA, NA, NA,...
## $ Image_URL    <chr> "http://images.brickset.com/sets/images/10246-1.jpg", ...
## $ GBP_MSRP     <dbl> 132.99, 149.99, 69.99, 59.99, 9.99, 16.99, 19.99, 49.9...
## $ USD_MSRP     <dbl> 159.99, 199.99, 99.99, 79.99, 9.99, 19.99, 24.99, 59.9...
## $ CAD_MSRP     <dbl> 199.99, 229.99, 119.99, NA, 12.99, 24.99, 29.99, 69.99...
## $ EUR_MSRP     <dbl> 149.99, 179.99, 89.99, 69.99, 9.99, 19.99, 24.99, 59.9...
## $ Packaging    <chr> "Box", "Box", "Box", "Box", "Box", "Box", "Box", "Box"...
## $ Availability <chr> "Retail - limited", "Retail - limited", "LEGO exclusiv...
Data summary
Name legosets
Number of rows 6172
Number of columns 14
_______________________
Column type frequency:
character 7
numeric 7
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
Item_Number 0 1 1 13 0 5854 0
Name 0 1 2 73 0 5519 4
Theme 0 1 4 28 0 115 0
Subtheme 0 1 0 32 2206 358 1
Image_URL 0 1 46 58 0 6172 0
Packaging 0 1 3 21 0 14 0
Availability 0 1 6 21 0 8 0

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100
Year 0 1.00 2004.71 8.91 1971.00 2000.00 2006.00 2012.00 2015.00
Pieces 112 0.98 215.17 356.20 0.00 30.00 82.00 256.25 5922.00
Minifigures 2672 0.57 2.85 2.72 1.00 1.00 2.00 4.00 32.00
GBP_MSRP 1980 0.68 23.45 31.93 0.00 5.99 12.99 29.99 509.99
USD_MSRP 355 0.94 27.90 39.32 0.00 6.00 14.99 34.99 789.99
CAD_MSRP 4190 0.32 46.34 58.46 2.99 12.99 24.99 54.99 789.99
EUR_MSRP 4399 0.29 35.98 46.61 0.00 9.99 19.99 39.99 699.99

Notice there are a lot of missing variables, especially when it comes to pricing - this will be important for when we calculate the means.


1c Pieces per year

Next, let’s look at how the number of pieces per set has changed over time. Because Duplo sets are much smaller (since they’re designed for toddlers), we’ll make a special indicator variable for them.

L02 aesthetics

Overview

The goal of this lab is to begin the process of unlocking the power of ggplot2 through constructing and experimenting with a few basic plots.

Datasets

We’ll be using data from the blue_jays.rda dataset which is already in the /data subdirectory in our data_vis_labs project. Below is a description of the variables contained in the dataset.

  • BirdID - ID tag for bird
  • KnownSex - Sex coded as F or M
  • BillDepth - Thickness of the bill measured at the nostril (in mm)
  • BillWidth - Width of the bill (in mm)
  • BillLength - Length of the bill (in mm)
  • Head - Distance from tip of bill to back of head (in mm)
  • Mass - Body mass (in grams)
  • Skull - Distance from base of bill to back of skull (in mm)
  • Sex - Sex coded as 0 = female or 1 = male

We’ll also be using a subset of the BRFSS (Behavioral Risk Factor Surveillance System) survey collected annually by the Centers for Disease Control and Prevention (CDC). The data can be found in the provided cdc.txt file — place this file in your /data subdirectory. The dataset contains 20,000 complete observations/records of 9 variables/fields, described below.

  • genhlth - How would you rate your general health? (excellent, very good, good, fair, poor)
  • exerany - Have you exercised in the past month? (1 = yes, 0 = no)
  • hlthplan - Do you have some form of health coverage? (1 = yes, 0 = no)
  • smoke100 - Have you smoked at least 100 cigarettes in your life time? (1 = yes, 0 = no)
  • height - height in inches
  • weight - weight in pounds
  • wtdesire - weight desired in pounds
  • age - in years
  • gender - m for males and f for females

Notice we are setting a seed. This signifies we will be doing something that relies on a random process (e.g., random sampling). In order for our results to be reproducible we set the seed. This ensures that every time you run the code or someone else does, it will produce the exact same output. It is good coding etiquette to set the seed towards the top of your document/code.

Exercises

Complete the following exercises.


Exercise 1

Using blue_jay dataset, construct the following scatterplots of Head by Mass:

  1. One with the color aesthetic set to Northwestern purple (#4E2A84), shape aesthetic set a solid/filled triangle, and size aesthetic set to 2.
  2. One using Sex or KnownSex mapped to the color aesthetic. That is, determine which is more appropriate and explain why. Also set the size aesthetic to 2.


Consider the color aesthetic in the plots for (1) and (2). Explain why these two usages of the color aesthetic are meaningfully different.


##       BirdID KnownSex BillDepth BillWidth BillLength  Head  Mass Skull Sex
## 1 0000-00000        M      8.26      9.21      25.92 56.58 73.30 30.66   1
## 2 1142-05901        M      8.54      8.76      24.99 56.36 75.10 31.38   1
## 3 1142-05905        M      8.39      8.78      26.07 57.32 70.25 31.25   1
## 4 1142-05907        F      7.78      9.30      23.48 53.77 65.50 30.29   0
## 5 1142-05909        M      8.71      9.84      25.47 57.32 74.90 31.85   1
## 6 1142-05911        F      7.28      9.30      22.25 52.25 63.90 30.00   0

Exercise 1.2


The first plot uses colors for a purley subjective reason, a preferance for purple, but does not have any aesthetic effect on the data. The second plot uses the aesthetic color to section the data into two groups (Female and Male); this plot is using color as part of the mapping of the data to aesthetics.


Exercise 2

Using a random subsample of size 100 from the cdc dataset (code provided below), construct a scatterplot of weight by height. Construct 5 more scatterplots of weight by height that make use of aesthetic attributes color and shape (maybe size too). You can define both aesthetics at the same time in each plot or one at a time. Just experiment. — Should be six total plots.


L03 categories & geom_smooth

Overview

The goal of this lab is to continue the process of unlocking the power of ggplot2 through constructing and experimenting with a few basic plots.

Datasets

We’ll be using data from the BA_degrees.rda and dow_jones_industrial.rda datasets which are already in the /data subdirectory in our data_vis_labs project. Below is a description of the variables contained in each dataset.

BA_degrees.rda

  • field - field of study
  • year_str - academic year (e.g. 1970-71)
  • year - closing year of academic year
  • count - number of degrees conferred within a field for the year
  • perc - field’s percentage of degrees conferred for the year

dow_jones_industrial.rda

  • date - date
  • open - Dow Jones Industrial Average at open
  • high - Day’s high for the Dow Jones Industrial Average
  • low - Day’s low for the Dow Jones Industrial Average
  • close - Dow Jones Industrial Average at close
  • volume - number of trades for the day

We’ll also be using a subset of the BRFSS (Behavioral Risk Factor Surveillance System) survey collected annually by the Centers for Disease Control and Prevention (CDC). The data can be found in the provided cdc.txt file — place this file in your /data subdirectory. The dataset contains 20,000 complete observations/records of 9 variables/fields, described below.

  • genhlth - How would you rate your general health? (excellent, very good, good, fair, poor)
  • exerany - Have you exercised in the past month? (1 = yes, 0 = no)
  • hlthplan - Do you have some form of health coverage? (1 = yes, 0 = no)
  • smoke100 - Have you smoked at least 100 cigarettes in your life time? (1 = yes, 0 = no)
  • height - height in inches
  • weight - weight in pounds
  • wtdesire - weight desired in pounds
  • age - in years
  • gender - m for males and f for females

Exercises

Exercise 1

The following exercises use the BA_degrees data set.

## # A tibble: 6 x 6
##   field    year_str  year  count  perc mean_perc
##   <fct>    <chr>    <dbl>  <dbl> <dbl>     <dbl>
## 1 Business 1970-71   1971 115396 0.137     0.204
## 2 Business 1975-76   1976 143171 0.155     0.204
## 3 Business 1980-81   1981 200521 0.214     0.204
## 4 Business 1985-86   1986 236700 0.240     0.204
## 5 Business 1990-91   1991 249165 0.228     0.204
## 6 Business 1995-96   1996 226623 0.195     0.204


Exercise 2

The following exercises use the dow_jones-industrial data set.

## # A tibble: 6 x 6
##   date        open  high   low close    volume
##   <date>     <dbl> <dbl> <dbl> <dbl>     <int>
## 1 2008-12-31 8666. 8843. 8665. 8776. 226760000
## 2 2009-01-02 8772. 9065. 8761. 9035. 213700000
## 3 2009-01-05 9027. 9034. 8892. 8953. 233760000
## 4 2009-01-06 8955. 9088. 8941. 9015. 215410000
## 5 2009-01-07 8997. 8997. 8720. 8770. 266710000
## 6 2009-01-08 8770. 8770. 8651. 8742. 226620000


Exercise 3

The following exercises use the cdc dataset.

## # A tibble: 6 x 9
##   genhlth   exerany hlthplan smoke100 height weight wtdesire   age gender
##   <fct>       <dbl>    <dbl>    <dbl>  <dbl>  <dbl>    <dbl> <dbl> <chr> 
## 1 good            0        1        0     70    175      175    77 m     
## 2 good            0        1        1     64    125      115    33 f     
## 3 good            1        1        1     60    105      105    49 f     
## 4 good            1        1        0     66    132      124    42 f     
## 5 very good       0        1        0     61    150      130    55 f     
## 6 very good       1        1        0     64    114      114    55 f

L04 geom_text & annotation

Overview

The goal of this lab is to continue the process of unlocking the power of ggplot2 through constructing and experimenting with a few basic plots.

Load Packages: tidyverse, gridExtra, ggrepel

Exercises

Exercise 1

The following plot uses the blue_jays.rda dataset.

#create caption that automatically grabs number of blue jays  
caption <- paste("Head length versus body mass for", nrow(blue_jays), "blue jays")

#add string wrap 
#will break the caption into multiple lines if longer than 40 characters
# '\n' is the line break code 
caption_print <- paste(strwrap(caption, 40), collapse ="\n") 

#create data set for top head size for each sex
topHead <- blue_jays %>% 
  #arrange largest to smallest
  arrange(desc(Head)) %>%
  # group by sex
  group_by(KnownSex) %>% 
  #take the top 2 head sizes  for each group 
  top_n(n = 2, wt = Head)

#'M' label will be put on the top male head size 
#'F' label will be put on the 2nd top female head size 
Labels <- topHead[c(1,4),]

#ANOTHER OPTIONS: lable dataframe 
#search by BirdID
Labels_anotheroption <- blue_jays  %>% 
  #select specific bird where you want the labels 
  filter(BirdID %in% c("1142-05914", "702-90567"))

#get range for x and y variables 
xrng <- range(blue_jays$Mass)
yrng <- range(blue_jays$Head)

#head length by body mass 
ggplot(blue_jays, aes(Mass, Head, color = KnownSex)) +
  geom_point(alpha = 0.6, size = 2) +
  annotate(
     "text"
    #put text in the top left corner of plot 
    , x = xrng[1], y = yrng[2]
    #label is the caption already create
    , label = caption
    #left justify 
    , hjust = 0
    # bottom justify 
    , vjust = 1
    #size the font
    , size = 4
    ) +
  xlab("Body mass (g)") +
  ylab("Head length (mm)") +
  #remove all legends; to remove just one legend put show.legend = FALSE into geom
  theme(legend.position = "none") +
  # add labels 
  geom_text(
    #use labels data set 
      data = Labels
    , aes(label = KnownSex)
    #nudget labels to the right 
    , nudge_x = 0.5
    )


Exercise 2

The following plots use the tech_stocks dataset.

Exercise 4

The next plot uses the cdc dataset.

Using Bilbo Baggins’ responses below to the CDC BRSFF questions, add Bilbo’s data point as a transparent (0.5) solid red circle of size 4 to a scatterplot of weight by height with transparent (0.1) solid blue circles of size 2 as the plotting characters. In addition, label the point with his name in red. Left justify and rotate the label so it reads vertically from bottom to top — shift it up by 10 pounds too. Plot should use appropriately formatted axis labels. Remember that the default shape is a solid circle.

  • genhlth - How would you rate your general health? fair
  • exerany - Have you exercised in the past month? 1=yes
  • hlthplan - Do you have some form of health coverage? 0=no
  • smoke100 - Have you smoked at least 100 cigarettes in your life time? 1=yes
  • height - height in inches: 46
  • weight - weight in pounds: 120
  • wtdesire - weight desired in pounds: 120
  • age - in years: 45
  • gender - m for males and f for females: m


Hint: Create a new dataset (maybe call it bilbo or bilbo_baggins) using either data.frame() (base R - example in book) or tibble() (tidyverse - see help documentation for the function). Make sure to use variable names that exactly match cdc’s variable names

L05 2d surface & geospatial

Overview

The goal of this lab is to explore more useful plots in ggplot2. Specifically we will be focusing on surface plots and geospatial plots (maps).

Challenges are not mandatory for students to complete. We highly recommend students attempt them though. We would expect graduate students to attempt the challenges.

Exercises

Complete the following exercises.


Challenge(s)

The following plots use the tidycensus package and few others, as well as using these directions.

Try using a different geographical area and a different variable from the ACS.

Plot 1: Manhatten and Household Median Income

Plot 2: Twin Cities and Percentage of Renter-occupied Units

L06 errorsbars & layers

Overview

The goal of this lab is to explore more plots in ggplot2. Specifically we will be focusing on error bars for uncertainty and practice using multiple layers.

Exercises


L07 scales, axes, & legends

Overview

The goal of this lab is to explore ways to manage and manipulate scales, axes, and legends within ggplot2.

Exercises

Exercise 3

Using cdc_smallconstruct a scatterplot of weight by height with the following requirements:

  • Size of plotting characters should be 3.
  • Color and shape should both identify genhlth.
  • One legend for both color and shape.
  • Legend title should be “General Health?” with a newline starting after general.
  • Legend categories should be ordered from excellent (top) to poor (bottom) with each word in category capitalized in the legend.
  • Legend should be placed in the lower right-hand corner of the plotting area.
  • Color should follow the "Set1" pallete.
  • Shape should have a solid triangle (17) for excellent, solid circle (19) for very good, an x (4) for poor, an hollow rotated square with an x in it (9) for fair, and a solid square (15) for good.
  • height values should be limited between 55 and 80.
  • height axis should display every 5th number between 55 and 80 and be appropriately labeled (i.e. 55 in, 60 in, …, 80 in). No axis title is necessary.
  • weight values should be limited between 100 and 300.
  • weight axis should be on log base 10 scale, but still display weights in pounds starting at 100 and displaying every 25 pounds until 300. Must be appropriately labeled (i.e. 100 lbs, 125 lbs, …, 300 lbs). No axis title is necessary.
  • Graph title should be CDC BRFSS: Weight by Height.
  • Minimal theme.

L08 positioning

Overview

The goal of this lab is to develop an understanding of facets, position, continue the exploration of other ggplot2 options/features.

Exercises

Exercise 2

Use the athletes_dat dataset — extracted from Aus_althetes.rd — to recreate the following graphic as precisely as possible. The cowplot package will be useful.



Hints:

  • Build each plot separately
  • Use cowplot::plot_grid() to combine them
  • Hex values for shading: #D55E0040 and #0072B240 (bottom plot), #D55E00D0 & #0072B2D0 (for top two plots) — no alpha
  • Hex values for outline of boxplots: #D55E00 and #0072B2
  • Boxplots should be made narrower; 0.5
  • Legend is in top-right corner of bottom plot
  • Legend shading matches hex values for top two plots
  • Bar plot lower limit 0, upper limit 95
  • rcc: red blood cell count; wcc: white blood cell count
  • Size 3 will be useful


L09 themes

Overview

The goal of this lab is to play around with the theme options in ggplot2

Exercises


Exercise 1

Use the cdc_small dataset to explore several pre-set ggthemes. The code below constructs the familiar scatterplot of weight by height and stores it in plot_01. Display plot_01 to observe the default theme. Explore/apply, and display at least 7 other pre-set themes from the ggplot2 or ggthemes package. Don’t worry about making adjustments to the figures under the new themes. Just get a sense of what the themes are doing to the original figure plot_01.

There should be at least 8 plots for this task. temp1 is pictured below.

Which theme or themes do you particularly like? Why? I think the default or theme_minmal() provide a clean option to view the day. If lines are not as important, theme_classic would work well to focus on the data shape (not necessarly the values). Void is great for maps when you don’t want the axes to show.

Exercise 3

Using data from cdc_small create a few (at least two) graphics (maybe one scatterplot and one barplot). Style the plots so they follow a “Northwestern” theme. Check out the following webpages to help create the theme:

Visual Identity


L10 data wrangling

Overview

The goal of this lab is to use data manipulation and transformation techniques to help use build a few plots.

Datasets

We’ll be using the mod_nba2014_15_advanced.txt and NU_admission_data.csv datasets — add both to the project’s data subdirectory. The codebook_mod_nba2014_15_advanced.txt file supplies a quick description of the variables in the mod_nba2014_15_advanced.txt dataset — suggest adding it to the data subdirectory as well. The undergraduate-admissions-statistics.pdf is the source for the NU_admission_data.csv dataset and it also contains the graphic/plot we will be attempting to re-create in the second exercise.

Exercises

Exercise 1

Using the mod_nba2014_15.txt dataset try to recreate/approximate the plot type featured in the http://fivethirtyeight.com/ article Kawhi Leonard Is The Most Well-Rounded Elite Shooter Since Larry Bird for any player of your choice for the 2014-2015 season. When calculating quartiles or considering players you may want to exclude players that played less than 10 games or played less than 5 minutes a game. That is, we only want to look for “qualified” players.

Exercise 2

Using NU_admission_data.csv create two separate plots derived from the single plot depicted in undergraduate-admissions-statistics.pdf. They overlaid two plots on one another by using two y-axes. Create two separate plots that display the same information instead of trying to put it all in one single plot — consider stacking them with cowplot::plot_grid(). Also, improve upon them by (1) fixing their error with the bar heights and (2) by using a “Northwestern” theme.

Also, practice placing all the text information on the appropriate plots. While I’m not a fan and think it is unnecessary for telling the actual story of the data, sometimes clients want this and there are those that think detailed labeling enhances the plot’s value — they do have a point. When including detailed labeling like this take care to pick label fonts and colors so the text doesn’t take away the from the message of the data (the trend in these plots). With these labels you could image removing the y-axes altogether so they don’t distracts the reader/consumer.

Which approach do you find communicates the information better, their single plot or the two plot approach? Why?

This information is directly connected (one is the the raw counts, the other the rate) - however, putting it all onto one plot makes it difficult to read and see trends. I think having two plots on top of eachother is a better way to show that the data are related but still allowing enough space to read.

Challenge(s)

No not have to complete.

Using NU_admission_data.csv try to re-create/approximate the single plot depicted in undergraduate-admissions-statistics.pdf. Fix their error concerning the bar heights. Might want to simply start with one of your plots from Exercise 2 and see if it can be modified.

ggplot(admission_bar, aes(year)) +
  
  #PRIMARY AXIS
  geom_col( aes(y=count, fill = status )) +
  scale_fill_manual(
      name = NULL
    , values = c(NW_black20, NW_yellow, NW_purple60)
    , labels = c("Not Admitted", "Admitted but did not attend", "Matriculants")
    , guide = guide_legend(reverse = TRUE)
  ) +
  
  #SECONDARY AXIS 
  geom_line( 
      data = admission_line
    , aes(y = rate*transform, color = status)
    , size = 1
  ) +
  geom_point( 
      data = admission_line
    , aes(y = rate*transform, color = status, shape = status)
    , size = 2
  ) +
  scale_color_manual(
      name = NULL
    , values = c(NW_purple, NW_orange)
    , labels = c("Yield Rate", "Admission Rate")
  ) +
  scale_shape_discrete(
      name = NULL
    , labels = c("Yield Rate", "Admission Rate")
  ) +
  
  #SCALING
  scale_x_continuous(
      NULL
    , limits = c(1998.25, 2018.75)
    , breaks = seq(1999, 2018)
    , minor_break = NULL
    , expand = c(0, 0)
  ) +
    scale_y_continuous(
      name = "Applications"
    , expand = c(0, 0)
    , breaks = y1_breaks
    , labels = scales::comma
    , sec.axis = sec_axis(
          ~./transform
        , breaks = y2_breaks
        , labels = scales::unit_format(suffix = "%")
        , name = "Rate"
      )
  ) +
    
    
  #GENERAL THEMES
  theme_minimal() +
  labs(
      title = "NORTHWESTERN UNIVERSITY"
    , subtitle = "Undergradudate Admission History by Entering Year"
    , caption = "SOURCE: Information Systems Office for Admissions & Financial Aid."
  ) +
  theme(
      legend.position = "top"
    , axis.title = element_text(color = NW_black80, family = "Georgia")
    , axis.text = element_text(color = NW_black80, family = "Georgia")
    , legend.text = element_text(color = NW_black80)
    , plot.title = element_text(
          color = NW_purple
        , family ="Georgia"
        , face = "bold"
        , hjust = 0.5
      )
    , plot.subtitle = element_text(
          color = NW_black80
        , family ="Georgia"
        , hjust = 0.5
      )
    , plot.caption = element_text(color = NW_black50)
  ) 

M1 Midterm 1

Datasets

We will need the instructor provided stephen_curry_shotdata_2014_15.txt dataset and the nbahalfcourt.jpg. The variables should be fairly straightforward after some inspection of the dataset, but we have provided a description of variables just in case.

  • GAME_ID - Unique ID for each game during the season
  • PLAYER_ID - Unique player ID
  • PLAYER_NAME - Player’s name
  • TEAM_ID - Unique team ID
  • TEAM_NAME - Team name
  • PERIOD - Quarter or period of the game
  • MINUTES_REMAINING - Minutes remaining in quarter/period
  • SECONDS_REMAINING - Seconds remaining in quarter/period
  • EVENT_TYPE - Missed Shot or Made Shot
  • SHOT_DISTANCE - Shot distance in feet
  • LOC_X - X location of shot attempt according to tracking system
  • LOC_Y - Y location of shot attempt according to tracking system



Exercises

Exercise 1

After replicating the plots provide a summary of what the graphics indicate about Stephen Curry’s shot selection (i.e. distance from hoop) and shot make/miss rate and how they relate/compare across distance and game time (i.e. across quarters/periods).

Plot 1

Unsurprisingly, there are the fewest shots during OT for both missed and made- which makes sense since not every game has an OT period. For all periods, the made shots for each quarter each have a longer IQR and lower median than the missed shots. The difference in the medians makes sense: larger distances make scoring points more difficult so shots made have a shorter distance that shots missed. In addition, there seems to be some variety between the medians by quarter for made shot (Q2 is the highest, where Q4 is significantly lower and a huge drop-off in OT); compared to missed shots where each of the regular periods (Q1, Q2, Q3, Q4) have roughly the same median and OT is the only one noticeably different. There also seems to be slightly less shots taken in the Q2 and Q4 than in Q1 and Q3 (both for shots made and shots missed) which may be do to playing time (some fancy baseball knowledge I don’t know).


Plot 2

The density graph shows a similar trend from the box plots: made shots on average have a shorter distance than missed shots. These densities are both bi-modal, peaking around 5f and again around 25 ft. The made shots has the higher pick at 5ft (easier to make shots at a shorter distance) and the missed shots has a higher peak at 25 ft (harder to make shots at a longer distance. Why is there this decrease in shots at the distances between? The 3pt-line is at ~24ft, which is why there is a large increase in shots taken just around and above that height. There is not much difference in difficult between taking a 23ft shot and a 25ft shot, but the former only gives you 2pts where the later gives you 3pts.


Exercise 2

After examining the two graphics, what do you conclude about Stephen Curry’s shot selection (i.e. distance form hoop) for the 2014-2015 season? Out of the four graphics (two from Exercise 1 and two from Exercise 2), which graphic(s) do you find the most useful when trying to understand Stephen Curry’s shot selection? If you find them all useful, explain what information is better communicated in each.

Plot 1

To understand Curry’s shot selection, the hex map is better as it shows the density of where he take shots. The point chart gives the same idea (more shots around the hoop and outside the 3pt line), but it is difficult to tell the difference in density because there are so many points - definitely a case of over-plotting The idea of looking at the location of the made and missed shots is interesting and I think it would be better to view a faceted hex map to compare shot density between made and missed shots. The results mirror the info from above; there is a higher density of missed shots outside the 3pt line compared to made shots and a higher density of made shots around the hoop compared to missed shots.

Exercise 3

Part 1

In 3-5 sentences, describe the core concept/idea and structure of the ggplot2 package.

ggplot2 is a data visualization tool that is more powerful and versatile than base R plots. ggplot2 allows the user to break down the plot into individual components that can be added, removed, or edited. ggplot2 is based on the Grammar of Graphics; which uses scales and layers to build a plot in a systematic fashion.

Part 2

Describe each of the following:

  1. ggplot(): creates a new plot; this plot is blank without any other specifications
  2. aes(): maps data to visual aesthetics
  3. geoms: specifies the type of geometric object to visualize (i.e. points, bars, etc.)
  4. stats: statistical transformation on the data rather than visualizing the data
  5. scales: translation of data to visual properties
  6. theme(): visual appearances that are not related to the data (i.e. background, legend position, title size, etc.)


Part 3

Explain the difference between using this code geom_point(aes(color = VARIABLE)) as opposed to using geom_point(color = VARIABLE).

geom_point(aes(color = VARIABLE)): This maps data to color based on value(s) of VARIABLE, e.g. if there are three levels of VARIABLE, the data will be mapped to three different color based on the level. This option also automatically creates a legend to show which color is assigned to which level(s) of VARIABLE.

geom_point(color = VARIABLE): This makes all points one color called VARIABLE. No legend is created because there is no mapping from data to aesthetics.

M2 Midterm 2

Datasets

We will be using the NH_2016pp_dem.txt and NH_2016pp_rep.txt datasets. NH_2016pp_dem.txt contains the raw vote count by county for each candidate for the 2016 New Hampshire Democratic presidential primary. NH_2016pp_rep.txt contains the raw vote count by county for each candidate for the 2016 New Hampshire Republican presidential primary.



Exercises

Complete the following exercises.


Exercise 1

Using the NH_2016pp_dem.txt and NH_2016pp_rep.txt datasets in conjunction with mapping data from the maps package replicate, as close as possible, the graphic below. Note the graphic is comprised of two plots displayed side-by-side. The plots both use the same shading scheme (i.e. scale limits and fill options). Hint: You will have to use pivot_longer(), left_join(), and other data manipulation functions.

Background Information: On Tuesday, February 9th 2016, New Hampshire held primaries for the Democratic and Republican Parties to apportion state delegates to nominate their respective party’s presidential nominee. Bernie Sanders (D) and Donald Trump (R) had very good nights. They both won every county in New Hampshire within their respective party’s primary. In the Democratic primary, Hillary Clinton was second in each county. In the Republican primary John Kasich was second in all but one county where he was in a virtual tie for second, but technically in third (thus the asterisk). The graphic below visualizes the ratio of the candidate with the highest vote total to the candidate with the second highest vote total in each county (a measure of strength for each county winner). The fact that we can replace first and second place with candidate names is simply a byproduct of how the primaries played out. Otherwise, the legend labels should have been “First to Second Ratio” or we might have implemented an alternative shading scheme.

After replicating the graphic provide a summary of how the two primaries relate to one another.

## # A tibble: 10 x 3
##    county       ratio_rep ratio_dem
##    <chr>            <dbl>     <dbl>
##  1 belknap           2.24      1.72
##  2 carroll           1.83      1.75
##  3 cheshire          2.08      2.43
##  4 coos              2.32      1.81
##  5 grafton           1.45      2.07
##  6 hillsborough      2.34      1.39
##  7 merrimack         1.77      1.48
##  8 rockingham        2.77      1.36
##  9 strafford         2.30      1.80
## 10 sullivan          2.16      2.37

There is a larger margin of victory in the democratic primary in the bottom left county, and a larger margin of victory in the Rebulican primary in the bottom right hand sign. This could mean that in these two counties there is very strong support for the lead candiate in the repsective parties. For example, Rockingham has a very high Trump to Kasich ratio but the smallest Sanders to Clinton ratio. This could mean that Republicans are Rockingham is very pro-Trump and in agreement; but the Democrats in this county do not have a consensus on a democratic candidate - is this because the county is so pro-Trump and more conservative?

L11 Shiny 1

Exercies

Exercies 1

Work through lesson 1 and lesson 2 which both contain an exercise for practice. In the case of lesson 1’s exercise you should have replaced the base R graphics code with ggplot code (i.e. make the histogram using ggplot2). Submit your shiny applications for lessons 1 and 2.

Lesson 1

#LESSON 1
library(shiny)
library(tidyverse)

# Define UI for app that draws a histogram ----
ui <- fluidPage(
  
  # App title ----
  titlePanel("Hello World!"),
  
  # Sidebar layout with input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      
      # Input: Slider for the number of bins ----
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 5,
                  max = 50,
                  value = 30)
      
    ),
    
    # Main panel for displaying outputs ----
    mainPanel(
      
      # Output: Histogram ----
      plotOutput(outputId = "distPlot")
      
    )
  )
)

# Define server logic required to draw a histogram ----
server <- function(input, output) {
  
  # Histogram of the Old Faithful Geyser Data ----
  # with requested number of bins
  # This expression that generates a histogram is wrapped in a call
  # to renderPlot to indicate that:
  #
  # 1. It is "reactive" and therefore should be automatically
  #    re-executed when inputs (input$bins) change
  # 2. Its output type is a plot
  output$distPlot <- renderPlot({
    
    
    ggplot(faithful, aes(waiting)) + 
      geom_histogram(
          color = "orange"
        , fill = "#75AADB"
        , bins = input$bins
      )+
      labs(
          x = "Waiting time to next erruption (in min)"
        , title = "Histogram of waiting times"
        , y = "Frequency"
      ) +
      theme_classic() + 
      theme(plot.title = element_text(size = 20))
    
#TEMPLATE HISTOGRAM EXAMPLE 
#    x    <- faithful$waiting
#    bins <- seq(min(x), max(x), length.out = input$bins + 1)
#    hist(x, breaks = bins, col = "#75AADB", border = "white",
#         xlab = "Waiting time to next eruption (in mins)",
#         main = "Histogram of waiting times")
    
  })
  
}

shinyApp(ui = ui, server = server)



Exercise 2

Create a shiny for the CDC data where the input is the number of bins and the output is a histogram of weight by gender.



Arend’s app (on shinnyapps server):


Exercise 3

Create an app with a state or country; explore options for text, images, and HTML tags.

#MINNESOTA MAP 
library(shiny)
library(tidyverse)
library(rvest) #for scraping data from mn web 
library(maps)


mn <- map_data("county", "minnesota") %>% 
  select(long, lat, group, id = subregion)


url <- "https://www.minnesota-demographics.com/counties_by_population"
webpage <- read_html(url)
tbls <- html_nodes(webpage, "table")

tbls_ls <- webpage %>%
  html_nodes("table") %>%
  html_table()

pop_mn_counties <- tbls_ls[[1]][-88, ] %>%
  mutate(
    Population = as.numeric(gsub(",", "",  Population))
    , County = tolower(gsub(" County", "", County))
    , County = ifelse(County == "st. louis", "st louis", County)
    , perc_pop = Population / sum(Population)
  ) %>%
  janitor::clean_names() 

mn_pop_map <- mn %>%
  left_join(., pop_mn_counties, by = c("id" = "county"))

# Define UI ----
ui <- fluidPage(
  titlePanel("Minnesota"),
  
  sidebarLayout(position = "left",
                sidebarPanel(
                    h3("Fun Facts:")
                  , strong("State Nickname:"), " Land of 10,000 Lakes",  br()
                  , strong("State Motto:"), " The Star of the North", br()
                  , strong("Population:"), "5.576 millsion (2017 est.)", br()
                  , strong("State Flag:")
                  , img(src = "flag.png", width = "80%"), br()
                  , strong("State Bird:"), " Loon"
                  , img(src = "loon.jpg", width = "80%")
                ),
                mainPanel(
                    plotOutput(outputId = "statemap")
                  , tags$ul(
                    tags$li("Minnesota was admitted as the 32nd state on May 11, 1858"), 
                    tags$li("Minnesota is ranked 12th in largest area and 22nd in population; nearly 55% of residents live in the Twin Cities metro area"), 
                    tags$li("Minnesota is known for a population that enjoys playing and watching hockey"), 
                    tags$li( "Minnesota still has a Virginia confederate flag that was caputred during the Battle of Gettysburg in 1863; Virigina has asked for the flag to be returned multiple times but ",
                        tags$a(href = "https://www.twincities.com/2017/08/20/minnesota-has-a-confederate-symbol-and-it-is-going-to-keep-it/"
                                      , "Minnesota has refused")
                              ), 
                    tags$li("Learn more on ", tags$a(href="https://en.wikipedia.org/wiki/Minnesota", "Wikipedia"))
                  )
                )
  )
)
# Define server logic ----
server <- function(input, output) {
  output$statemap <-  renderPlot({
    ggplot(mn_pop_map, aes(x = long, y = lat, fill = perc_pop)) +
      geom_polygon(aes(group = group) , color = "grey35") +
      scale_fill_continuous(
        name = "Percent of Population"
        , breaks = c(0.05, 0.10, 0.15, 0.20)
        , labels = c("5%", "10%", "15%", "20%")
      ) +
    coord_quickmap() +
      theme_void()
  })
  
}

# Run the app ----
shinyApp(ui = ui, server = server)

L12 Shiny 2

Exercises

Exercise 2

Create a shiny for the CDC data where the input is the number of bins and variable and the output is a histogram of weight by the given variable.

library(shiny)
library(tidyverse)
library(skimr)

# https://stackoverflow.com/questions/48106504/r-shiny-how-to-display-choice-label-in-selectinput 
# https://shiny.rstudio.com/reference/shiny/1.4.0/tabsetPanel.html

cdc <- read_delim(file = "cdc.txt", delim = "|") %>%
  mutate(
    genhlth = factor(
      genhlth
      , levels = c("excellent", "very good", "good", "fair", "poor")
      , labels = c("Excellent", "Very Good", "Good", "Fair", "Poor")
    )
    , hlthplan = factor(
      hlthplan
      , levels = c(0, 1)
      , labels = c("No", "Yes")
    )
    , exerany = factor(
      exerany
      , levels = c(0, 1)
      , labels = c("No", "Yes")
    )
    , smoke100 = factor(
      smoke100
      , levels = c(0, 1)
      , labels = c("No", "Yes")
    )
    , gender = factor(
      gender
      , levels = c("f", "m")
      , labels = c("Female", "Male")
    )
  )

# Define UI for app that draws a histogram ----
ui <- fluidPage(
  
  # App title ----
  titlePanel("CDC BRFSS Histograms"),
  
  sidebarLayout(
    position = "right", 
    
    sidebarPanel(
      
      selectInput("x_var", label = "Select Variable:",
                  choices = list(
                      "Actual Weight" = "weight"
                    , "Desired Weight" = "wtdesire"
                    , "Height" = "height"
                  ),  selected = "weight"
          ), #end of select input 
      
      
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 5,
                  max = 50,
                  value = 30,
                  animate = animationOptions(interval = 1000, loop = FALSE)
        ),  #end of slider input 
      
      radioButtons("fill_var", label = "Select Fill/Legend Variable", 
                   choices = list(
                       "General Health" = "genhlth"
                     , "Health Coverage" = "hlthplan"
                     , "Exercised in Past Month" = "exerany"
                     , "Smoked 100 Cigarettes" = "smoke100"
                     , "Gender" = "gender"
                     , "None" = "None"
                     ), selected = "genhlth"
          ) #end of radio buttons 
      
    ), #end of side bar panel 
    
    # Main panel for displaying outputs ----
    mainPanel(
      tabsetPanel(
        tabPanel("Plot", plotOutput("plot")),
        tabPanel("Summary", verbatimTextOutput("summary_x"), verbatimTextOutput("summary_fill")) 
      ) #end tabsetPanel 
    ) #end mainPanel
  ) #end sidebar layout 
) # end fluid page 

fill_names <- c(
  "General Health" = "genhlth"
  , "Health Coverage" = "hlthplan"
  , "Exercised in Past Month" = "exerany"
  , "Smoked 100 Cigarettes" = "smoke100"
  , "Gender" = "gender"
)

x_names <- c(
  "Actual Weight in Pounds" = "weight"
  , "Desired Weight in Pounds" = "wtdesire"
  , "Height in Inches" = "height"
)

# Define server logic required to draw a histogram ----
server <- function(input, output) {

#PLOT OUTPUT   
  output$plot <- renderPlot({
    
    #other option 
    #var_hist <- case_when(
    #  input$var_x == "Actual Weight" ~ pull(cdc, weight)
    #)
    
    
    fill <- cdc[[input$fill_var]]
    fill_name <- names(fill_names)[fill_names == input$fill_var]
    
    
    x <- cdc[[input$x_var]]
    x_name <- names(x_names)[x_names == input$x_var]
    
    
      base_plot <- ggplot(cdc, aes(x)) + 
        scale_fill_discrete(name = NULL) +
        labs(
          x =  x_name 
          , y = "Count"
          , subtitle = fill_name
        ) +
        theme_minimal() +
        theme(
          plot.subtitle = element_text(hjust = 0.5)
          , legend.position = "top"
          , plot.background = element_rect(fill = "grey95", color = NA)
          , panel.grid.major = element_line(color = "grey80")
        ) 
      
      if (input$fill_var == "None") {
        base_plot + geom_histogram(
            fill = "skyblue"
          , color = "black"
          , bins = input$bins
        )
      } else {
        base_plot + geom_histogram(
          aes(fill = fill)
          , color = "black"
          , bins = input$bins
        )
      } #end of if else 
      
  }) #end of renderplot
  
############ END OF PLOT OUTPUT
  
# SUMMARY X OUTPUT
  output$summary_x <- renderPrint({ 
    print(skim(cdc, input$x_var), include_summary = FALSE, strip_metadata = TRUE)
  }) #end of render
  
########### END OF SUMMARY X OUTPUT 
  
  # SUMMARY FILL OUTPUT
  output$summary_fill <- renderPrint({
    if (input$fill_var == "None") {
      X <- NULL 
    } else {
    print(skim(cdc, input$fill_var), include_summary = FALSE, strip_metadata = TRUE)
    } #end of if else 
  }) #end of render
  
########### END OF SUMMARY FILL  OUTPUT 
  
} #end of server 

shinyApp(ui = ui, server = server)

# rsconnect::deployApp('Eichlersmith_Martha_L12/CDC_plot')



This app can be accessed at mareichler-nw.shinyapps.io/cdc_plot/ ; it is also embedded below.